import json
import random
import time

import requests

from app.modules1.PublicApproach import get_token_result
from app.modules1.common.encryptionUtils import getResult1
from config import DB


# 获取全部供应商月结、实销实结
def _fetch_paginated_vendor_data():
    """通过API分页获取指定结算类型的供应商数据"""
    # 获取token
    token = get_token_result()
    session = requests.Session()
    # 分页功能
    all_vendors_data = []
    page_index = 0
    page_size = 1000
    url = "https://web.jackyun.com/jkyun/erp-baseinfo/vendinfo/vend/list"
    base_headers = {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "module_code": "mainframe",
        "origin": "https://web.jackyun.com",
        "referer": "https://web.jackyun.com/home/mainframe_web.html",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "Windows",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36",
        "x-requested-with": "XMLHttpRequest",
    }
    target_settlement_types = "月结,OEM月结,实销实结,OEM实销实结"  # 目标结算类型

    print("开始从API获取供应商数据...")
    while True:
        headers = base_headers.copy()
        headers["authorization"] = f"Bearer {token}"

        condition_json = {
            "serviceType": "search.vend.list",
            "businessType": "search.vend.list",
            "pageIndex": str(page_index),
            "pageSize": str(page_size),
            "isBlockup": 0,
            "searchFieldName": "code",
            "searchValue": "",
            "platformCodes": "",
            "level": "",
            "abbreviation": "",
            "isJlinkId": "",
            "settType": "",
            "addressLeft": "",
            "leader": "",
            "tel": "",
            "fax": "",
            "developDateStart": "",
            "developDateEnd": "",
            "assistantCode": "",
            "flagData": "",
            "remindMsg": "",
            "memo": "",
            "linkTimeStart": "",
            "linkTimeEnd": "",
            "noLinkDays": "",
            "paymentMethodId": "",
            "email": "",
            "levelCode": "",
            "goodsSupplyAddress": "",
            "companyNameHeader": "$lk$新疆最西域电子商务有限公司",
            "vendExtendStr": f'[{{"fieldName": "field8$in", "value": "{target_settlement_types}"}}]',
            "cols": '["vendId", "code", "name", "className", "companyName", "departName", "purchOfficeName", "levelName", "field8"]',
        }
        data_payload = {
            "pageIndex": str(page_index),
            "pageSize": str(page_size),
            "sortField": "",
            "sortOrder": "",
            "conditionJson": json.dumps(condition_json),
        }

        try:
            requests_data = getResult1(token, data_payload)
            response = session.post(
                url,
                headers=headers,
                data=requests_data,
                timeout=(10, 30),
                proxies={"http": None, "https": None},
            )

            if response.status_code != 200:
                print(f"请求失败，状态码: {response.status_code}")
                print(f"错误响应头: {response.headers}")
                try:
                    error_detail = response.json()
                    print(
                        f"错误详情: {json.dumps(error_detail, ensure_ascii=False, indent=2)}"
                    )
                except json.JSONDecodeError:
                    print(f"错误响应内容: {response.text}")
                return None  # 请求失败返回 None

            print(f"正在获取第 {page_index + 1} 页供应商数据...")
            result = response.json()
            current_page_data = result.get("result", {}).get("data", [])

            if not current_page_data:
                print("没有更多供应商数据了")
                break

            all_vendors_data.extend(current_page_data)
            print(f"当前页获取 {len(current_page_data)} 条数据")
            print(f"累计已获取 {len(all_vendors_data)} 条数据")

            delay = random.uniform(1.2, 4.0)  # 稍微降低延迟上限
            print(f"等待: {delay:.1f} 秒后继续...")
            time.sleep(delay)
            page_index += 1

        except requests.exceptions.RequestException as e:
            print(f"请求过程中发生错误: {e}")
            return None  # 网络或请求错误返回 None
        except Exception as e:
            print(f"处理响应时发生未知错误: {e}")
            return None  # 其他未知错误

    session.close()
    print(f"API数据获取完成，共获取 {len(all_vendors_data)} 条供应商记录。")
    # return _print_vendors(all_vendors_data)
    return _save_vendors_to_db(all_vendors_data)

# 打印获取到的供应商数据
def _print_vendors(all_vendors_data):
    """打印获取到的供应商数据"""
    if not all_vendors_data:
        print("没有供应商数据可供打印。")
        return
    # print(all_vendors_data)
    print("获取到的供应商数据:")
    for vendor in all_vendors_data:
        print(f"供应商名称:{vendor.get('name')}")
        print(f"供应商ID: {vendor.get('vendId')}")
        print(f"供应商编号: {vendor.get('code')}")
        print(f"账期情况:{vendor.get('field8')}")
        print(f"分类:{vendor.get('className')}")
        print(f"所属公司:{vendor.get('companyName')}")
        print(f"所属部门:{vendor.get('departName')}")
        print("------------------------------------------------------------------------")

# 把获取到的供应商保存到数据库
def _save_vendors_to_db(all_vendors_data):
    """将供应商数据批量保存或更新到数据库"""
    if not all_vendors_data:
        print("没有供应商数据需要保存。")
        return False

    conn = None
    cursor = None
    try:
        conn = DB()
        cursor = conn.cursor()

        # 先清空表中的所有数据
        truncate_sql = "TRUNCATE TABLE DZ_vendor_info"
        cursor.execute(truncate_sql)
        print("已清空 DZ_vendor_info 表中的所有数据")

        insert_data = []
        for vendor in all_vendors_data:
            if vendor.get("vendId") == "2050150659100837376":
                print(f"跳过供应商: {vendor.get('name')} (ID: {vendor.get('vendId')})")
                continue
            # 准备插入/更新的数据元组
            insert_data.append(
                (
                    vendor.get("vendId"),
                    vendor.get("code"),
                    vendor.get("name"),
                    vendor.get("className"),
                    vendor.get("companyName"),
                    vendor.get("departName"),
                    vendor.get("purchOfficeName"),
                    vendor.get("levelName"),
                    vendor.get("field8"),  # settlement_type
                )
            )

        if not insert_data:
            print("没有有效数据可供插入/更新数据库。")
            return False

        sql = """
        INSERT INTO DZ_vendor_info (
            vendor_id, code, vendor_name, class_name,
            company_name, depart_name, purch_office_name,
            level_name, settlement_type
        ) VALUES (
            %s, %s, %s, %s, %s, %s, %s, %s, %s
        ) ON DUPLICATE KEY UPDATE
            code = VALUES(code),
            vendor_name = VALUES(vendor_name),
            class_name = VALUES(class_name),
            company_name = VALUES(company_name),
            depart_name = VALUES(depart_name),
            purch_office_name = VALUES(purch_office_name),
            level_name = VALUES(level_name),
            settlement_type = VALUES(settlement_type)
        """
        # 执行批量插入/更新
        cursor.executemany(sql, insert_data)
        conn.commit()
        print(f"成功批量保存或更新 {len(insert_data)} 条供应商数据到数据库！")
        return True

    except Exception as e:
        if conn:
            conn.rollback()
        print(f"保存供应商数据到数据库时出错: {str(e)}")
        return False
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()


if __name__ == '__main__':
    _fetch_paginated_vendor_data()

